﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Dynamic;
using System.Workflow.Activities.Rules;
using System.Data.Common;
using System.Configuration;

namespace DbStreamConverter
{
    public static class LinqExtension
    {
        public static IEnumerable<T> AsEnumerable<T>(this IDataReader dr) where T : new()
        {

            List<Action<object, object>> setters = null;

            while (dr.Read())
            {
                if (setters == null)
                {
                    setters = new List<Action<object, object>>();
                    var dict = typeof(T).GetProperties().ToDictionary(x => x.Name.ToLower(), x => x);
                    for (int index = 0; index < dr.FieldCount; index++)
                    {
                        var name = dr.GetName(index).ToLower();
                        setters.Add(dict.ContainsKey(name) ?
                            new Action<object, object>(delegate(object target, object value) { dict[name].SetValue(target, value, null); })
                            : null);
                    }
                }
                T newObject = new T();
                for (int index = 0; index < dr.FieldCount; index++)
                {

                    if (!dr.IsDBNull(index))
                    {
                        var setter = setters[index];
                        if (setter != null) setter(newObject, dr.GetValue(index));
                    }
                }
                yield return newObject;
            }
            dr.Close();
        }

        public static IEnumerable<T> BulkCopy<T>(this IEnumerable<T> items, string destinationTableName, string dbProvider, string connectionString, List<string> props, int timeout = 0)
        {
            var db = DbProviderRepository.GetDbSchemaProvider(dbProvider, connectionString);
            db.BulkCopy<T>(items, destinationTableName, props, timeout);
            return items;
        }
    }
}
